import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.lang.String;

public class twiface extends HttpServlet {
  private ConnectionPool connectionPool;
  
  public void doGet(HttpServletRequest req,
                    HttpServletResponse resp) throws ServletException, IOException 
  {
    String table;
    PrintWriter out = resp.getWriter();
    try {
		String query = ""; 
		/// get all the parameters
		// 1. user ID
		String userID = ((String) req.getParameter("id"));
		// 2. twitter screen name
		String scrName = ((String) req.getParameter("scrname"));

		// 3. insert -- validate
		String opInsert = (String) req.getParameter("insert");
		if (opInsert != null) {
			// validate names
			validateString(userID, "User ID");
			validateString(scrName, "Screen Name");
			// we will create an insert query
			query = "insert into vr_proj values('"+userID+"', '"+scrName+"')";
			out.println("Query: " + query);
		}
		// 4. update -- validate
		String opUpdate = (String) req.getParameter("update");
		if (opUpdate != null) {
			// validate names
			validateString(userID, "User ID");
			validateString(scrName, "Screen Name");
			// we will create an update query
			query = "update vr_proj set screen_name='"+scrName+"' where userid='"+userID+"'";
			out.println("Query: " + query);
		}
		// 5. list -- validate
		String opList = (String) req.getParameter("list");
		if (opList != null) {
			// we will create a list query
			query = "select userid, screen_name from vr_proj";
		}
		// 6. get particular value 
		String opFetch = (String) req.getParameter("getscrname");
		if (opFetch != null){
			// we will create a fetch query
			query = "select screen_name from vr_proj where userid='"+userID+"'";
		}
		// 7. check if given osid exists
		String opExists = (String) req.getParameter("exists");
		if (opExists != null){
			// we will create a fetch query
			query = "select count(screen_name) \"Count\" from vr_proj where userid='"+userID+"'";
		}
		
      Connection connection = connectionPool.getConnection();
      DBResults results = DatabaseUtilities.getQueryResults(connection,query, false);
      connectionPool.free(connection);
	  if (opList != null) {
		//table = results.toHTMLTable("#FFADFF");
		if (results != null){
			table = results.getResultsAsJSON();
		} else {
			table = "i really do not know ";
		}
	  } else if (opFetch != null) {
		if (results != null){
			table = results.getFirstRowAsJSON();
		} else {
			table = "i really do not know ";
		}
	  } else if (opExists != null){
		if (results != null){
			table = results.getFirstRowAsJSON();
		} else {
			table = "i really do not know ";
		}
	  } else {
		table = "";
	  }
    } catch(Exception e) {
      table = "Error: " + e;
	  e.printStackTrace(out);
    }
    // Prevent the browser from caching the response. See
    // Section 7.2 of Core Servlets and JSP for details.
	if (table != ""){
		//resp.setContentType("text/plain");
		resp.setContentType("application/json");
		resp.setHeader("Pragma", "no-cache"); // HTTP 1.0
		resp.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
		String title = "Connection Pool Test";
		out.println(table);
	}	
  }

  // validates string names
  protected void validateString(String str, String PropertyName) throws Exception{
	try{
		if (str.length() == 0){
			throw new Exception("Invalid" + PropertyName);
		}	
	} catch (Exception e) {
		throw new Exception("Invalid" + PropertyName);
	}
  }
  
  /** Initialize the connection pool when servlet is
   *  initialized. To avoid a delay on first access, load
   *  the servlet ahead of time yourself or have the
   *  server automatically load it after reboot.
   */
  
  public void init() {
    int vendor = DriverUtilities.ORACLE;
    String driver = DriverUtilities.getDriver(vendor);
    String host = "pizza.mcs.csueastbay.edu";
    String dbName = "cs1db";
    String url = DriverUtilities.makeURL(host, dbName, vendor);
    String username = "cs12618";
    String password = "cs12618";
    try {
      connectionPool =
        new ConnectionPool(driver, url, username, password,
                           initialConnections(),
                           maxConnections(),
                           true);
    } catch(SQLException sqle) {
      System.err.println("Error making pool: " + sqle);
      getServletContext().log("Error making pool: " + sqle);
      connectionPool = null;
    }
  }

  public void destroy() {
    connectionPool.closeAllConnections();
  }

  /** Override this in subclass to change number of initial
   *  connections.
   */
  
  protected int initialConnections() {
    return(10);
  }

  /** Override this in subclass to change maximum number of 
   *  connections.
   */

  protected int maxConnections() {
    return(50);
  }
}

